package com.dove.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dove.common.Constants;
import com.dove.common.Result;
import com.dove.entity.User;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

import com.dove.service.IRoleService;
import com.dove.entity.Role;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author dove
 * @since 2022-03-26
 */
@RestController
@RequestMapping("/roles")
public class RoleController {
    @Resource
    private IRoleService roleService;

    @PostMapping
    public Result save(@RequestBody Role role) {
        boolean b = roleService.saveOrUpdate(role);
        if (b) {
            return Result.success("保存成功");
        }
        return Result.error("保存失败");
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean b = roleService.removeById(id);
        if (b) {
            return Result.success("删除成功");
        }
        return Result.error("删除失败");
    }

    //删除选中
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        boolean b = roleService.removeByIds(ids);
        if (b) {
            return Result.success("批量删除成功");
        }
        return Result.error("批量删除失败");
    }

    @GetMapping
    public Result findAll() {
        List<Role> list = roleService.list();
        if (list == null) {
            return Result.error("查询全部失败");
        }
        return Result.success(list);
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        Role role = roleService.getById(id);
        if (role == null) {
            return Result.error("id查询失败");
        }
        return Result.success(role);
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String name) {
        IPage<Role> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Role> qw = new QueryWrapper<>();
        if (!"".equals(name)) {
            qw.like("name", name);
        }
        return Result.success(roleService.page(page, qw));
    }

    @PostMapping("/roleMenu/{roleId}")
    public Result roleMenu(@PathVariable Integer roleId,@RequestBody List<Integer> menuIds) {
        roleService.setRoleMenu(roleId,menuIds);
            return Result.success("保存成功");
    }

    @GetMapping("/roleMenu/{roleId}")
    public Result getRoleMenu(@PathVariable Integer roleId) {
        List<Integer> menuIds = roleService.findByRoleId(roleId);
        return Result.success(menuIds);
    }
}
